﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using PlatformNetCore.Common;
using PlatformNetCore.Common.Utility;
using PlatformNetCore.Entity;
using PlatformNetCore.Web.Models;
using System;
using UEditorNetCore;

namespace PlatformNetCore.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<PlatformContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMemoryCache();
            services.AddUEditorService();
            services.AddMvc(options =>
            {
                options.ModelBinderProviders.Insert(0, new JObjectModelBinderProvider());//加入JobjectModelBinderProvider绑定
            }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddNewtonsoftJson(options =>
            {
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //数据格式首字母小写
                //options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //数据格式按原样输出
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //忽略空值
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

            //Cookie(1)添加 Cookie 服务
            services.AddAuthentication(CommonConst.AdminAuthenticationScheme)
                  //后台管理员cookie服务
                  .AddCookie(CommonConst.AdminAuthenticationScheme, options =>
                  {
                      options.LoginPath = "/Account/Login";//登录路径
                      options.LogoutPath = "/Account/Logout";//退出路径
                      options.AccessDeniedPath = new PathString("/Account/Login");//拒绝访问页面
                      options.Cookie.Path = "/";
                  });
             
            //开启IdentityServer4验证
            //string oAuthUrl = Configuration.GetSection("AppSettings").GetSection("OAuthUrl").Value;
            //services.AddAuthentication("Bearer").AddIdentityServerAuthentication(options =>
            //{
            //    options.Authority = oAuthUrl;
            //    options.RequireHttpsMetadata = false;
            //    options.ApiName = "PlatformNetCore.OAuth2";
            //});
            
            services.AddSingleton<IPathProvider, PathProvider>();
            services.AddHttpContextAccessor();
            return RegisterAutofac(services);
        }

        private IServiceProvider RegisterAutofac(IServiceCollection services)
        {
            //实例化Autofac容器
            var builder = new ContainerBuilder();
            //将Services中的服务填充到Autofac中
            builder.Populate(services);
            //新模块组件注册
            builder.RegisterModule<AutofacModuleRegister>();
            //创建容器
            var Container = builder.Build();
            IOCContainerManager.Initialize(Container);
            //第三方IOC接管 core内置DI容器 
            return new AutofacServiceProvider(Container);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //app.UseHttpsRedirection();
                //app.UseExceptionHandler("/Account/Error");
                app.UseStatusCodePagesWithRedirects("/errors/{0}");
            }

            app.UseStaticFiles();

            app.UseRouting();

            //app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Account}/{action=Index}/{id?}");
            });
            

        }
    }
}
